<?php

namespace app\stores\controller\miniapp\goods;

use app\BaseController;

use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\goods\GoodsWriteOffModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsGroupModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\common\logic\SmsLogic;

use app\beautiful\logic\LogsLogic;

use app\beautiful\logic\MemberWalletLogic;

use app\common\model\CustomerServiceModel;
use app\common\model\ShopModel;
use app\stores\logic\order\OrderLogic;

use app\stores\logic\PinTuanLogic;

use app\beautiful\model\mall\GoodsModel;

use app\beautiful\model\mall\PinTuanGoodsModel;

use app\beautiful\model\mall\PinTuanGoodsSkuModel;

use app\beautiful\model\mall\PinTuanGroupModel;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\PinTuanOrderItemModel;

use app\beautiful\model\order\PinTuanOrderModel;

use app\beautiful\model\logs\GoodsViewsModel;

use app\beautiful\model\setting\SettingSmsModel;

use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;



class PinTuan extends BaseController{

    public function getPinTuanGoodsList()

    {

        $today= date("Y-m-d",$this->request->time());

        $where=[

            ['status','=',1],

            ['is_delete','=',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

        ];

        //获取可用的商品id集合

        $goods_where=[

            ['status','=',1],

            ['is_delete','=',0],

            ['is_open_yu','=',0],

        ];

        if($this->request->shopId) $goods_where[]=['shop_id','=',$this->request->shopId];

        $goods_ids=GoodsModel::where($goods_where)->column('goods_id') ?? [];

        $where[]=['goods_id','in',$goods_ids];

        if($this->request->shopId) $where[]=['shop_id','=',$this->request->shopId];

        $order=['is_tui'=>'desc','fictitious_take_count'=>'desc','pin_tuan_price'=>'asc'];

        $datas=PinTuanGoodsModel::with(['goods'=>function($query){

            $query->field('goods_id,name,original_price,cover_img,total_value,type');

        }])->where($where)

            ->order($order)

            ->field('shop_id,pin_tuan_goods_id,group_num,goods_id,pin_tuan_price,fictitious_take_count,quota')

            ->limit($this->request->limit)

            ->page($this->request->page)

            ->select()

            ->toArray();

        $return['datas']=$datas;



        return $this->success($return);



    }



    public function getPinTuanGoodsDetail()

    {

        $today= date("Y-m-d",$this->request->time());

        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        //保存用户门店中等级信息
        if($this->request->shopId && $this->request->memberId){
            saveMemberLevel($this->request->shopId,$this->request->memberId);
        }

        //判断秒杀

        if(null === $pin_tuan_goods = PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error('拼团不存在');

        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error('拼团不存在');

        if($pin_tuan_goods->is_delete == 1) return $this->error('拼团不存在');

        if($pin_tuan_goods->status != 1) return $this->error('拼团已下架');

        if($pin_tuan_goods->start_time > $today) return $this->error('拼团还未开始');

        if($pin_tuan_goods->end_time < $today) return $this->error('拼团已结束');



        //判断秒杀商品

        if(null === $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$pin_tuan_goods->goods_id])->json(['goods_details'],true)->find()) return $this->error('拼团商品不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('拼团商品不存在');

        if($goods->is_delete == 1) return $this->error('拼团商品不存在');

        if($goods->status != 1) return $this->error('拼团商品已下架');





        if($pin_tuan_goods->is_have_sku==1){

            $sku_return=PinTuanGoodsSkuModel::list(['pin_tuan_goods_id'=>$pin_tuan_goods_id,'shop_id'=>$this->request->shopId],['pgs.add_time'=>'asc'],1,999,'pgs.pin_tuan_goods_sku_id,pgs.start_sales_num,pgs.name,pgs.original_price,pgs.pin_tuan_price,pgs.quota,sd.group_detail_name as unit');

            $sku = $sku_return['list'];
        }



       $detail=[

            'pin_tuan_goods_id'=>$pin_tuan_goods_id,

            'goods'=>[

                'goods_id'=>$goods->goods_id,

                'rotation'=>$goods->rotation,

                'name'=>$goods->name,

                'original_price'=>$goods->original_price,

                'goods_details'=>$goods->goods_details,

                'cover_img'   => $goods->cover_img,

                'type'=>$goods->type,

                'unit'=> $goods['unit']?$goods['unit']['group_detail_name']:null

            ],

            'group_num'=>$pin_tuan_goods->group_num,

            'pin_tuan_price'=>$pin_tuan_goods->pin_tuan_price,

            'quota'=>$pin_tuan_goods->quota,

            'fictitious_take_count'=>$pin_tuan_goods->fictitious_take_count,

            'is_have_sku'=>$pin_tuan_goods->is_have_sku,

            'sku'=>isset($sku) ? $sku :[],

            'pin_tuan_info'=>$pin_tuan_goods->pin_tuan_info,

            'start_sales_num'=>$pin_tuan_goods->start_sales_num

        ];



        $return['detail']=$detail;

        //记录拼团对应的产品访问记录

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods->goods_id

        ]);

        return $this->success($return);



    }

    public function getPinTuanSetMealDetail()

    {
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);

        $today= date("Y-m-d",$this->request->time());

        //保存用户门店中等级信息
        if($this->request->shopId && $this->request->memberId){
            saveMemberLevel($this->request->shopId,$this->request->memberId);
        }
        //判断拼团

        if(null === $pin_tuan_goods = PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error('拼团不存在');

        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error('拼团不存在');

        if($pin_tuan_goods->is_delete == 1) return $this->error('拼团不存在');

        if($pin_tuan_goods->status != 1) return $this->error('拼团已下架');

        if($pin_tuan_goods->start_time > $today) return $this->error('拼团还未开始');

        if($pin_tuan_goods->end_time < $today) return $this->error('拼团已结束');

        //判断拼团商品

        if(null === $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$pin_tuan_goods->goods_id,'type'=>3])->json(['discount_detail','use_limit_detail'],true)->find()) return $this->error('拼团套餐不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('拼团套餐不存在');

        if($goods->is_delete == 1) return $this->error('拼团套餐不存在');

        if($goods->status != 1) return $this->error('拼团套餐已下架');


        //套餐分组
        $goods_group = GoodsGroupModel::with(['groupDetail'=>function($query){
                $query->where(['is_delete'=>0]);
            }])->where([['goods_id','=',$pin_tuan_goods->goods_id],['is_delete','=',0]])
                ->field('goods_group_id,group_name,type,num,choose_num,is_choose_same')
                ->select()->toArray() ?? [];

        $total_price = 0;
        foreach ($goods_group as $k=>$v){

            $detail_return = $this->groupDetail($v['groupDetail'],$total_price);

            $total_price += $detail_return['total_price'];

            $goods_group[$k]['groupDetail'] = $detail_return['groupDetail'];

        }

        $shop = ShopModel::with(['detail'])->where(['shop_id'=>$this->request->shopId])->find();

        $detail=[

            'pin_tuan_goods_id'=>$pin_tuan_goods_id,

            'goods'=>[

                'goods_id'=>$goods->goods_id,

                'rotation'=>$goods->rotation,

                'name'=>$goods->name,

                'original_price'=>$goods->original_price,

                'total_value'=>$goods->total_value,

                'goods_details'=>$goods->goods_details,

                'cover_img'   => $goods->cover_img,

                'type'=>$goods->type,

                'group'=>$goods_group,

                'unit'=>isset($goods['unit'])?$goods['unit']['group_detail_name']:null

            ],

            'group_num'=>$pin_tuan_goods->group_num,

            'pin_tuan_price'=>$pin_tuan_goods->pin_tuan_price,

            'quota'=>$pin_tuan_goods->quota,

            'fictitious_take_count'=>$pin_tuan_goods->fictitious_take_count,

            'is_have_sku'=>$pin_tuan_goods->is_have_sku,

            'sku'=>isset($sku) ? $sku :[],

            'pin_tuan_info'=>$pin_tuan_goods->pin_tuan_info,

            'distance'=>get_distance($lat,$lng,$shop->detail->t_lat,$shop->detail->t_lng),

            'shop_name'=>$shop->name,

        ];



        $return['detail']=$detail;

        //记录拼团对应的产品访问记录

        $GoodsViewsModel = new GoodsViewsModel();

        $GoodsViewsModel->save([

            'shop_id'   => $this->request->shopId,

            'goods_id'  => $goods->goods_id

        ]);

        return $this->success($return);



    }
    protected function groupDetail($groupDetail,$total_price){
        foreach ($groupDetail as $k=>$v){
            if($v['goods_id']){
                $goods = GoodsModel::where(['shop_id'=>$this->request->shopId,'goods_id'=>$v['goods_id'],'is_delete'=>0])->find();
                $groupDetail[$k]['goods_name'] = $goods->name;
                $groupDetail[$k]['original_price'] = $goods->original_price;

                $groupDetail[$k]['unit'] = GoodsOtherSkuDetailModel::where(['shop_id'=>$this->request->shopId,'other_sku_detail_id'=>$goods['unit_id'],'is_delete'=>0])->value('group_detail_name');

                $total_price += $goods->original_price;
            }else{
                $groupDetail[$k]['goods_name'] = $v['goods_name'];
                $groupDetail[$k]['original_price'] = $v['original_price'];
                $groupDetail[$k]['unit'] = $v['unit_name'];

            }
            $total_price += $groupDetail[$k]['original_price'];
            $groupDetail[$k]['total_goods_price'] = $v['original_price']*$v['num'];
        }
        $return['total_price'] = $total_price;
        $return['groupDetail'] = $groupDetail;
        return $return;
    }

    //获取我的订单

    public  function getMyPintuanOrderList(){

        $where = [

            ['member_id','=', $this->request->memberId]

        ];
        //存在的门店
        $shop_ids = ShopModel::where(['open_status'=>1])->column('shop_id');
        $where[] = ['shop_id','In',$shop_ids];
        
        $datas = PinTuanOrderModel::with(['oneitem','item'])->where($where)

                ->field('pin_tuan_group_id,pin_tuan_order_id,is_chief,status,add_time,need_pay')

                ->limit($this->request->limit)

                ->page($this->request->page)

                ->order(['pin_tuan_order_id' => 'desc'])

                ->select()->append([

                    'djs_time','group_djs_time'

                ])->toArray();

        return $this->success(['list'=>$datas]);

    }

    

    public function getGroupList()

    {



        $today= date("Y-m-d",$this->request->time());

        $pin_tuan_goods_id=$this->request->param('pin_tuan_goods_id/d',0);



        //判断秒杀

        if(null === $pin_tuan_goods = PinTuanGoodsModel::find($pin_tuan_goods_id)) return $this->error('拼团不存在');

        if($pin_tuan_goods->shop_id != $this->request->shopId) return $this->error('拼团不存在');

        if($pin_tuan_goods->is_delete == 1) return $this->error('拼团不存在');

        if($pin_tuan_goods->status != 1) return $this->error('拼团已下架');

        if($pin_tuan_goods->start_time > $today) return $this->error('拼团还未开始');

        if($pin_tuan_goods->end_time < $today) return $this->error('拼团已结束');



        //判断秒杀商品

        if(null === $goods = GoodsModel::find($pin_tuan_goods->goods_id)) return $this->error('拼团商品不存在');

        if($goods->shop_id != $this->request->shopId) return $this->error('拼团商品不存在');

        if($goods->is_delete == 1) return $this->error('拼团商品不存在');

        if($goods->status != 1) return $this->error('拼团商品已下架');



        $group=PinTuanGroupModel::with(['chief'=>function($query){

            $query->field('member_id,nick_name,face,member_num');

               

        }])->where([

            ['shop_id','=',$this->request->shopId],

            ['pin_tuan_goods_id','=',$pin_tuan_goods->pin_tuan_goods_id],

            ['status','=',1],

            ['add_time','>=',$this->request->time()-86400]

        ])->field('pin_tuan_group_id,chief_id,pin_tuan_goods_id,add_time,group_size,num')

            ->append(['djs_time','remain_num'])

            ->limit(5)

            ->select()->toArray();

        foreach ($group as $k=>$v){
            $order = PinTuanOrderModel::where(['pin_tuan_group_id'=>$v['pin_tuan_group_id'],'shop_id'=>$this->request->shopId,'member_id'=>$v['chief_id']])->find();
            $group[$k]['pin_tuan_order_id'] = $order?$order->pin_tuan_order_id:null;
        }

        return $this->success(['datas'=>$group]);

    }



    public function createOrder()

    {

        $logistics_type=$this->request->param('logistics_type/d');

        $receiving_name=$this->request->param('receiving_name');

        $receiving_mobile=$this->request->param('receiving_mobile');

        $pin_tuan_group_id=$this->request->param('pin_tuan_group_id/d',0);

        $receiving_address_province=$this->request->param('receiving_address_province');

        $receiving_address_city=$this->request->param('receiving_address_city');

        $receiving_address_county=$this->request->param('receiving_address_county');

        $receiving_address_info=$this->request->param('receiving_address_info');

        $total_price = $this->request->param('total_price/f',0);

        $use_integral = $this->request->param('use_integral/d',0);

        $coupon_id = $this->request->param('coupon_id/d',0);

        $goods=$this->request->param('goods/a',[]);

        $from_type = $this->request->param('from_type/d',1);

        $order_send_time = $this->request->param('order_send_time');

        $mix_pay_type = $this->request->param('mix_pay_type');

        $params=[

            'member_id'=>$this->request->memberId,

            'logistics_type'=>$logistics_type,

            'receiving_name'=>$receiving_name,

            'receiving_mobile'=>$receiving_mobile,

            'receiving_address_province'=>$receiving_address_province,

            'receiving_address_city'=>$receiving_address_city,

            'receiving_address_county'=>$receiving_address_county,

            'receiving_address_info'=>$receiving_address_info,

            'total_price'=>$total_price,

            'use_integral'=>$use_integral,

            'coupon_id'=>$coupon_id,

            'goods'=>$goods,

            'pin_tuan_group_id'=>$pin_tuan_group_id,

            'from_type'=>$from_type,

            'order_send_time'=>$order_send_time,

            'mix_pay_type'=>$mix_pay_type


        ];

        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            $order_id=$order_logic['pin_tuan']->createOrder($params);

            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }





    }



    public function cancelPay()

    {

        $order_id=$this->request->param('order_id/d',0);

        $params=[

            'order_id'=>$order_id,

            'member_id'=>$this->request->memberId,

        ];

        Db::startTrans();

        try{

            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);

            $pin_tuan_logic->cancelPay($params);

            Db::commit();

            return $this->success('取消拼团成功');

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function moneyPay()

    {

        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = PinTuanOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1){

            return $this->error('订单不在未支付状态');

        }

        $time = time() - 1800;//订单30分钟

        if($order->add_time < $time){ //如果 订单超过30分钟则不能支付了

            return $this->error('订单支付已经超时了，不能继续支付');

        }

        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){

            return $this->error('订单不存在');

        }

        Db::startTrans();

        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->need_pay,$this->request->memberId,$this->request->shopId);
                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;

                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = PinTuanOrderModel::find($order_id);
            if(!empty($order->member_coupon_id)){

                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 1){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                $myCoupon->status = 1;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);

            }

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);

            if(!empty($order->use_integral)){ //使用积分

                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);

                if($res == false){

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }

            }

            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);

            if($needPay <= 0){

                Db::rollback();

                $this->error('支付金额不正确');

            }

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',4);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $res = $MemberWalletLogic->useBalance($needPay, $order->total_price + $order->freight , 8); //商城购物使用

                if($res == false){

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }
            }

            $order->is_paid = 1;

            $order->pay_time = time();

            $order->status = 2;

            $order->pay_type = 'money';
            if(empty($mix_pay_type)) $order->money = $order->pay_money;
            $order->save();



            //支付成功后的

            $params=[

                'order_id'=>$order->pin_tuan_order_id,

                'member_id'=>$this->request->memberId,

            ];

            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);

            $pin_tuan_logic->payOk($params);



            //发送短信给管理员

            try{

                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

                if(null !== $sms_setting){

                    if($sms_setting->order_notice_admin==1){

                        $sms_logic= new SmsLogic();

                        $params=[

                            'money'=>$needPay,

                        ];

                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');

                    }

                }

            }catch (\Exception $e){



            }



            Db::commit();

            return $this->success('储值卡支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }

    /*钱包支付*/
    public function platformMoneyPay()

    {

        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = PinTuanOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1){

            return $this->error('订单不在未支付状态');

        }

        $time = time() - 1800;//订单30分钟

        if($order->add_time < $time){ //如果 订单超过30分钟则不能支付了

            return $this->error('订单支付已经超时了，不能继续支付');

        }

        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){

            return $this->error('订单不存在');

        }

        Db::startTrans();

        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->need_pay,$this->request->memberId,$this->request->shopId);
                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;
                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = PinTuanOrderModel::find($order_id);

            if(!empty($order->member_coupon_id)){

                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 1){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                $myCoupon->status = 1;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);

            }

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);

            if(!empty($order->use_integral)){ //使用积分

                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);

                if($res == false){

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }

            }

            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);

            if($needPay <= 0){

                Db::rollback();

                $this->error('支付金额不正确');

            }

            $order->is_paid = 1;

            $order->pay_time = time();

            $order->status = 2;

            $order->pay_type = 'platform_money';
            if(empty($mix_pay_type)) $order->platform_money = $order->pay_money;
            $order->save();

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',4);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->request->shopId, $this->request->memberId);

                $res = $StoresMemberWalletLogic->usePlatformMoney($needPay, 0, 0, $order->pin_tuan_order_id, 1); //商城购物使用

                if ($res == false) {

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }
            }
            //支付成功后的

            $params=[

                'order_id'=>$order->pin_tuan_order_id,

                'member_id'=>$this->request->memberId,

            ];

            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);

            $pin_tuan_logic->payOk($params);



            //发送短信给管理员

            try{

                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

                if(null !== $sms_setting){

                    if($sms_setting->order_notice_admin==1){

                        $sms_logic= new SmsLogic();

                        $params=[

                            'money'=>$needPay,

                        ];

                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');

                    }

                }

            }catch (\Exception $e){



            }



            Db::commit();

            return $this->success('钱包支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }


    public function cancelPinTuan()

    {

        $order_id = $this->request->param('order_id/d',0);

        $params=[

            'order_id'=>$order_id,

            'member_id'=>$this->request->memberId,

        ];

        Db::startTrans();

        try{
            $pin_tuan_logic = new PinTuanLogic($this->request->shopId);

            $pin_tuan_logic->cancelPinTuan($params);

            Db::commit();

            return $this->success('取消成功');

        }catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function getPinTuanDetail()

    {
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $pin_tuan_order_id=$this->request->param('pin_tuan_order_id/d',0);

        if($pin_tuan_order_id==0) return $this->error('拼团不存在');



        //判断拼团订单存不存在

        if(null === $pin_tuan_order = PinTuanOrderModel::where(['pin_tuan_order_id'=>$pin_tuan_order_id])->append(['pay_time_format','order_time','pay_type_mean'])->find()){

            return $this->error('拼团不存在');

        }


        if($pin_tuan_order->member_id != $this->request->memberId) return $this->error('拼团不存在');

        //判断拼团订单商品存不存在

        if(null === $pin_tuan_order_item = PinTuanOrderItemModel::where('pin_tuan_order_id',$pin_tuan_order_id)->find()){

            return $this->error('拼团不存在');

        }


        //如果已经参团了，判断团队存不存在

        if($pin_tuan_order->pin_tuan_group_id !=0 ){

            if(null === $pin_tuan_group = PinTuanGroupModel::with(['pinTuanGoods'])->where(['pin_tuan_group_id'=>$pin_tuan_order->pin_tuan_group_id])->find()){

                return $this->error('拼团不存在');

            }
        }

        $pin_tuan_goods = PinTuanGoodsModel::with(['goods'])->where(['pin_tuan_goods_id'=>$pin_tuan_order_item['goods_id']])->find();

        if($pin_tuan_order->status == 3){
            //已成团
            $order = GoodsOrderModel::with(['skus'])->where(['pin_tuan_order_id'=>$pin_tuan_order_id])->find();
            if(null === $order) return $this->error('拼团订单不存在');
            $order = $order->toArray();
            $goods_type = $order['skus'][0]['type'];

        }else{
            if(null === $pin_tuan_goods) return $this->error('拼团商品不存在');
            $pin_tuan_goods = $pin_tuan_goods->toArray();
            $goods_type = $pin_tuan_goods['goods']['type'];
        }

        $goods_info=[

            'goods_name'=>$pin_tuan_order_item->goods_name,

            'goods_cover_img'=>$pin_tuan_order_item->goods_cover_img,

            'goods_sku_id'  => $pin_tuan_order_item->goods_sku_id,

            'goods_sku_name'=>$pin_tuan_order_item->goods_sku_name,

            'goods_original_price'=>$pin_tuan_order_item->goods_original_price,

            'goods_price'=>$pin_tuan_order_item->goods_price,

            'group_size'=>$pin_tuan_order_item->group_size,

            'goods_type'=>$goods_type,

            'goods_id'=>$pin_tuan_goods['goods_id']

        ];



        $members=PinTuanOrderModel::where([

          ['shop_id','=',$pin_tuan_order->shop_id],

          ['pin_tuan_group_id','=',$pin_tuan_order->pin_tuan_group_id],

          ['status','in',[2,3,-1,-2]],

          ['is_paid','=',1]

      ])->field('member_id,member_face,member_name,is_chief')->order(['is_chief'=>'desc'])

          ->select()->toArray();

        $shop = ShopModel::with(['detail'=>function($query){
            $query->field('shop_id,t_lat,t_lng');
        }])->where(['shop_id'=>$pin_tuan_order->shop_id])
            ->find();

        $return=[

            'pin_tuan_order_id' => $pin_tuan_order_id,

            'pin_tuan_group_id'=>$pin_tuan_order->pin_tuan_group_id,

            'status'=>$pin_tuan_order->status,

            'status_means'=>$pin_tuan_order->status_means,

            'goods_info'=>$goods_info,

            'djs_time' => $pin_tuan_order->djs_time,

            'need_pay' => $pin_tuan_order->need_pay, 

            'group_djs_time' => $pin_tuan_order->group_djs_time,

            'members'=>$members,

            'shop_id'=>$pin_tuan_order->shop_id,

            'shop_lng'=>$shop->detail->t_lng,

            'shop_lat'=>$shop->detail->t_lat,
        ];



        if($pin_tuan_order->pin_tuan_group_id !=0 ){

            $djs_time=$pin_tuan_group->add_time + 86400 - time();

            $group=[

                'remain_num'=>$pin_tuan_group->group_size - $pin_tuan_group->num,

                'djs_time'=>$djs_time > 0 ? $djs_time : 0

            ];

            $return['group']=$group;

        }
        $order_info = [];
        if($pin_tuan_order->status == 3){
            $order = GoodsOrderModel::where(['pin_tuan_group_id'=>$pin_tuan_order->pin_tuan_group_id,'member_id'=>$this->request->memberId])->find();
            $shop_info = ShopModel::info(['shop_id'=>$pin_tuan_order->shop_id,'is_delete'=>0]);
            $service = CustomerServiceModel::where(['customer_service_id'=>$shop_info['customer_service_id']])->find();
            $order_info['integral_balance'] = $order->integral_balance;
            $order_info['youhui_balance'] = $order->youhui_balance;
            $order_info['status'] = $order->status;
            $order_info['order_id'] = $order->order_id;
            $order_info['is_paid'] = $order->is_paid;
            $order_info['receiving_name'] = $order->receiving_name;
            $order_info['receiving_mobile'] = $order->receiving_mobile;
            $order_info['receiving_address_province'] = $order->receiving_address_province;
            $order_info['receiving_address_city'] = $order->receiving_address_city;
            $order_info['receiving_address_county'] = $order->receiving_address_county;
            $order_info['receiving_address_info'] = $order->receiving_address_info;
            $order_info['logistics_type'] = $pin_tuan_order->logistics_type;
            $order_info['freight_type'] = $order->freight_type;
            $order_info['freight'] = $order->freight;
            $order_info['hours'] = $order->hours;
            $order_info['order_type'] = $order->order_type;
            $order_info['order_send_time'] = $pin_tuan_order->order_send_time?json_decode($pin_tuan_order->order_send_time,true):null;
            $order_info['shop_name'] = $shop_info->name;
            $order_info['shop_logo'] = $shop_info['detail']['logo'];
            $order_info['shop_address'] = $shop_info['detail']['address'];
            $order_info['shop_tel'] = $service?$service->mobile:null;
            $order_info['distance'] = get_distance($lat,$lng,$shop_info['detail']['lat'],$shop_info['detail']['lng']);
            $order_info['order_sn'] = $order?$order->order_sn:null;
            $order_info['verify_code'] = $order?$order->verify_code:null;
            $order_info['pay_time'] = $pin_tuan_order->pay_time_format;
            $order_info['order_time'] = $pin_tuan_order->order_time;
            $order_info['num'] = $order->status == 8?0:$pin_tuan_order_item->goods_num;
            $order_info['total_price'] = $pin_tuan_order->total_price;
            $order_info['need_pay'] = $pin_tuan_order->need_pay;
            $order_info['coupon_money'] = $pin_tuan_order->coupon_money;
            $order_info['pintuan_reduce_money'] = $pin_tuan_order_item->goods_original_price - $pin_tuan_order_item->goods_price;
            $order_info['pay_type_mean'] = $pin_tuan_order->pay_type_mean;
            $order_info['platform_money'] = $pin_tuan_order->platform_money;
            $order_info['money'] = $pin_tuan_order->money;
            $order_info['weixin'] = $pin_tuan_order->weixin;
            $set_meal_info = $this->setMealInfo($pin_tuan_order,$pin_tuan_order_item->toArray());
            $order_info['set_meal_info'] = $set_meal_info;
                //是否核销完
            $remain_num = $set_meal_info['remain_num'];
            $is_many_hx = $set_meal_info['is_many_hx'];
//            $group_detail = OrderGoodsGroupDetailModel::where(['pin_tuan_order_id'=>$pin_tuan_order_id,'is_delete'=>0])->select()->toArray();
//            foreach ($group_detail as $k=>$v){
//                $remain_num += $v['remain_num'];
//                if($v['use_condition']!=1){
//                    $is_many_hx = 1;
//                }
//            }
            //使用情况
            $un_one_order_goods_group_detail_ids = OrderGoodsGroupDetailModel::where(['pin_tuan_order_id'=>$pin_tuan_order_id])->where('use_condition','<>',1)->column('order_goods_group_detail_id');
            $write_off = GoodsWriteOffModel::with(['orderGoodsGroupDetail'])->where(['order_id'=>$order->order_id])->select()->toArray();
            $write_offs = [];
            foreach ($write_off as $k=>$v){
                if(in_array($v['orderGoodsGroupDetail']['order_goods_group_detail_id'],$un_one_order_goods_group_detail_ids)){
                    $write_offs[$k] = $v;
                    $write_offs[$k]['goods_name'] = $v['orderGoodsGroupDetail']['goods_name'];
                    $write_offs[$k]['sku_name'] = $v['orderGoodsGroupDetail']['sku_name'];
                    $write_offs[$k]['unit'] = $v['orderGoodsGroupDetail']['unit'];
                }
                unset($write_off[$k]['orderGoodsGroupDetail']);
            }
            $all_once_write_off_time = (!$write_offs && !$un_one_order_goods_group_detail_ids && $write_off)?$write_off[0]['add_time']:null;
            $order_info['remain_num'] = $remain_num;
            $order_info['is_many_hx'] = $is_many_hx;
            $order_info['is_end'] = $remain_num<1?1:0;
            $order_info['write_off'] = $write_offs;
            $order_info['all_once_write_off_time'] = $all_once_write_off_time;
        }


        $return['order_info'] = $order_info;

        return $this->success($return);

    }

    public function setMealInfo($order,$item){
        //分组与分组详情
        $group = OrderGoodsGroupModel::with(['orderGoodsGroupDetail'=>function($query){
            $query->where(['is_delete'=>0])->order(['sort'=>'desc']);
        }])->where(['pin_tuan_order_id'=>$order->pin_tuan_order_id,'pin_tuan_order_item_id'=>$item['pin_tuan_order_item_id'],'is_delete'=>0])
            ->select()->toArray();
        //是否核销完
        $remain_num = 0;
        $is_many_hx= 0;
        foreach ($group as $k=>$v){
            $return = $this->orderGoodsGroupDetail($v['orderGoodsGroupDetail']);
            $remain_num += $return['remain_num'];
            $is_many_hx = $return['is_many_hx'];
            $group[$k]['orderGoodsGroupDetail'] = $return['orderGoodsGroupDetail'];
        }
        $item['group'] = $group;
        //套餐其他信息
        $goods = OrderGoodsModel::where(['is_delete'=>0,'pin_tuan_order_id'=>$order->pin_tuan_order_id,'pin_tuan_order_item_id'=>$item['pin_tuan_order_item_id']])->json(['use_limit_detail'],true)->find();
        if($goods){
            $goods->goods_name = $item['goods_name'];

            $goods->goods_cover_img = $item['goods_cover_img'];

            $goods->original_price = $item['goods_original_price'];
            //到期时间
            if($order['status'] !=1 && $order['status']!=-3){
                $end_time = goodsEndTime($goods,$order);

                $goods->start_time = $end_time['start_time'];

                $goods->end_time = $end_time['end_time'];
            }else{
                $goods->start_time = null;

                $goods->end_time = null;
            }

        }
        //使用情况
        $write_off = GoodsWriteOffModel::with(['orderGoodsGroupDetail'])->where(['pin_tuan_order_id'=>$order->pin_tuan_order_id])->select()->toArray();
        foreach ($write_off as $k=>$v){
            $write_off[$k]['goods_name'] = $v['orderGoodsGroupDetail']['goods_name'];
            $write_off[$k]['sku_name'] = $v['orderGoodsGroupDetail']['sku_name'];
            $write_off[$k]['unit'] = $v['orderGoodsGroupDetail']['unit'];

        }

        $datas['num'] = $item['goods_num'];
        $datas['goods'] = $goods;
        $datas['item'] = $item;
        $datas['write_off'] = $write_off;
        $datas['remain_num'] = $remain_num;
        $datas['is_many_hx'] = $is_many_hx;
        return $datas;

    }
    protected function orderGoodsGroupDetail($orderGoodsGroupDetail){
        $remain_num = 0;
        $is_many_hx = 0;
        foreach ($orderGoodsGroupDetail as $k=>$v){
            $remain_num += $v['remain_num'];
            if($v['use_condition']!=1){
                $is_many_hx= 1;
            }
            $orderGoodsGroupDetail[$k]['total_goods_price'] = $v['goods_original_price']*$v['num'];
        }
        $return['is_many_hx'] = $is_many_hx;
        $return['remain_num'] = $remain_num;
        $return['orderGoodsGroupDetail'] = $orderGoodsGroupDetail;
        return $return;
    }

    public function showPinTuanDetail()

    {
        $shop_id = $this->request->param('shop_id/d',0);
        $pin_tuan_group_id=$this->request->param('pin_tuan_group_id/d',0);

        if($pin_tuan_group_id==0) return $this->error('拼团不存在');



        //判断团队

        if(null === $pin_tuan_group = PinTuanGroupModel::find($pin_tuan_group_id)){

            return $this->error('拼团不存在');

        }

        if($pin_tuan_group->add_time + 86400 - time() <0) return $this->error('拼团时间已过');

        $djs_time=$pin_tuan_group->add_time + 86400 - time();

        $group=[

            'remain_num'=>$pin_tuan_group->group_size - $pin_tuan_group->num,

            'djs_time'  =>$djs_time > 0 ? $djs_time : 0,

            'status'    => $pin_tuan_group->status,

            'group_size'=>$pin_tuan_group->group_size,

            'num'       => $pin_tuan_group->num,

        ];

        //判断拼团商品

        $pin_tuan_goods=PinTuanGoodsModel::where([

            ['status','=',1],

            ['is_delete','=',0],

            ['pin_tuan_goods_id','=',$pin_tuan_group->pin_tuan_goods_id],

        ])->field('pin_tuan_goods_id,goods_id,pin_tuan_price,quota,take_count,fictitious_take_count,is_have_sku,group_num')

            ->find();

        if(null === $pin_tuan_goods) return $this->error('拼团商品不存在');



        $goods=GoodsModel::find($pin_tuan_goods->goods_id);

        empty($goods) && $this->error('商品不存在');

        $pin_tuan_goods->toArray();

        $pin_tuan_goods['goods'] = $goods->toArray();

        if($pin_tuan_goods['is_have_sku']==1){
            $sku=PinTuanGoodsSkuModel::where([

                ['shop_id','=',$shop_id],

                ['pin_tuan_goods_id','=',$pin_tuan_goods->pin_tuan_goods_id],

                ['quota','>',0],

                ['is_delete','=',0]

            ])->select()->toArray();

            $pin_tuan_goods['sku']=$sku;

        }



        //获取参团人员

        $members=PinTuanOrderModel::where([

            ['shop_id','=',$this->request->shopId],

            ['pin_tuan_group_id','=',$pin_tuan_group_id],

            ['status','IN',[2,3,-1,-2]],

            ['is_paid','=',1]

        ])->field('member_id,member_face,member_name,is_chief')->order(['is_chief'=>'desc'])

            ->select()->toArray();

        

         

        $return=[

            'goods'=>$pin_tuan_goods,

            'group'=>$group,

            'members'=>$members

        ];

        $return['group']=$group;

        $return['pmember'] = null;

        //判断邀请人

        $member_id = $this->request->param('member_id/d',0);

        if(!empty($member_id)){

            if(null === $pmember = MemberModel::find($member_id)) return $this->error('邀请人不存在');

            if($pmember->shop_id != $this->request->shopId) return $this->error('邀请人不存在');

            $return['pmember'] = [

                'member_id'=>$pmember->member_id,

                'nick_name'=>$pmember->nick_name,

                'face'=>$pmember->face,

            ];

        }

      

       

        return $this->success($return);



    }



}

